// pages/personal/couponConfirm/couponConfirm.js
var app = getApp();
var utils = require('../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isHide: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    that.mycouponTap();
  },
  buy: function(e) {
    var that = this;
    this.setData({
      currentIndex: e.currentTarget.dataset.index,
      // isHide: false
    }, function() {
      utils.showLoading();
      var param = {
        id: that.data.couponList[that.data.currentIndex].id
      };
      utils.http("/api/v1/com_coupon/add_order", param, function(res) {
        utils.hideLoading();
        if (res.state == 1) {
          wx.requestPayment({
            timeStamp: res.datas.timeStamp,
            nonceStr: res.datas.nonceStr,
            package: res.datas.package,
            signType: res.datas.signType,
            paySign: res.datas.paySign,
            success() {
              that.paySuccessCallback(res);
            },
            fail(res) {
              that.setData({
                buttonClicked: false
              })
            }
          })

        } else {
          utils.message(res.datas);
        }
      })
    })
  },
  // 获取我的优惠券可使用数据 
  mycouponTap: function() {
    var that = this;
    utils.http("/api/v1/com_coupon/com_coupon_list", {}, function(res) {
      that.setData({
        couponList: res.datas
      })
    })
  },
  //支付方式
  paymentTypeTap: function(e) {
    var id = e.currentTarget.dataset.id;
    var currentBut = id;
    this.setData({
      currentBut: currentBut,
      typePay: e.currentTarget.dataset.type,
      buttonClicked: false
    })
  },
  //立即支付
  onOrderSuccessTap: function(e) {
    var that = this;
    if (that.data.buttonClicked == false) {
      utils.showLoading();
      var param = {
        id: that.data.couponList[that.data.currentIndex].id
      };
      utils.http("/api/v1/com_coupon/add_order", param, function(res) {
        utils.hideLoading();
        if (res.state == 1) {
          if (that.data.typePay == "wx_pay") {
            wx.requestPayment({
              timeStamp: res.datas.timeStamp,
              nonceStr: res.datas.nonceStr,
              package: res.datas.package,
              signType: res.datas.signType,
              paySign: res.datas.paySign,
              success() {
                that.paySuccessCallback(res);
              },
              fail(res) {
                that.setData({
                  buttonClicked: false
                })
              }
            })
          } else {
            that.paySuccessCallback(res);
          }
        } else {
          utils.message(res.datas);
        }
      })
    }
  },
  paySuccessCallback: function(res) {
    var that = this;
    wx.showToast({
      title: '支付成功',
    })
  },
  onColseTap: function() {
    this.setData({
      isHide: true
    })
  },
})